package com.glodon.paas.activity.client;

import static javax.ws.rs.core.MediaType.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MultivaluedMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.glodon.paas.activity.api.bean.Activity;
import com.glodon.paas.activity.api.bean.ActivityIn;
import com.glodon.paas.exception.PaasRuntimeException;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.util.ObjectUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;

public class ActivityClientHttpImpl implements ActivityClient {

    private static Logger  logger         = LoggerFactory.getLogger(ActivityClientHttpImpl.class);

    private Integer appId          = 0;
    private String  activityApiUrl = "http://127.0.0.1:8080/activity/api/internal";
    private boolean enable         = true;

    public void setAppId(Integer appId) {
        this.appId = appId;
    }

    public Integer getAppId() {
        return appId;
    }

    public void setActivityApiUrl(String activityApiUrl) {
        this.activityApiUrl = activityApiUrl;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    /**
     * 发送活动数据 先通过接口直接发送，发送失败可以尝试向queue
     */
    public void publish(ActivityIn activity) {
        if (!enable) {
            return;
        }
        // 活动对象属性设置
        activity.setAppId(appId);
        activity.setPublishTime(new Date());

        try {
            // rest参数
            MultivaluedMap<String, String> params = new MultivaluedMapImpl();
            params.add("appId", String.valueOf(activity.getAppId()));
            params.add("activityType", String.valueOf(activity.getActivityType()));

            ClientResponse client = createResource().queryParams(params)
                    .type(APPLICATION_JSON_TYPE).accept(APPLICATION_JSON_TYPE)
                    .entity(ObjectUtil.toJson(activity)).post(ClientResponse.class);

            if (client.getStatus() == 204) {
                // 成功，返回值是null
                if (logger.isDebugEnabled()) {
                    logger.debug("publishActivity ok:activity=" + ObjectUtil.toJson(activity));
                }
                return;
            } else if (client.getStatus() == 200) {
                if (logger.isDebugEnabled()) {
                    logger.debug("publishActivity ok:activity=" + ObjectUtil.toJson(activity));
                }
                return;
            } else {
                String msg = "publishActivity error:ClientResponseStatus=" + client.getStatus();
                throw PaasServerExceptionFactory.internalAPIException(msg, null);
            }
        } catch (PaasRuntimeException e) {
            logger.error(e.getMessage());
            throw e;
        }catch(Exception e){
            throw PaasServerExceptionFactory.internalAPIException("publishActivity ", e);
        }
    }

    /**
     * 默认时间倒序
     * 可用参数 
     * @param receiverId   必须，接受者ID
     * @param appId
     * @param moduleId
     * @param activityType
     * @param itemId
     * @param itemType
     * @param subItemId
     * @param actorId       发送者ID
     * @param earlierTime   较新的时间,毫秒
     * @param laterTime     较早的时间,毫秒
     * @param count         需要查询记录数
     * @param needRender    是否 需要使用模板渲染：值可以是true，false，1，0
     * @return
     */
    @Override
    public Activity[] query(Map<String, String> params) {
        // 参数
        MultivaluedMap<String, String> paramMap = new MultivaluedMapImpl();
        for (String key : params.keySet()) {
            paramMap.add(key, params.get(key));
        }

        WebResource resource = createResource().queryParams(paramMap);
        ClientResponse client = resource.type(APPLICATION_JSON_TYPE).get(ClientResponse.class);

        if (client.getStatus() == 204) {
            // 成功，返回null
            return new Activity[0];
        }
        if (client.getStatus() != 200) {
            // 异常
            logger.error("queryActivity error:" + client);
            return new Activity[0];
        }

        List<Activity> list = null;
        String str = null;
        try {
            str = client.getEntity(String.class);
            list = JSON.parseArray(str, Activity.class);
        } catch (Exception e) {
            logger.error("call server or parse json to array error,str=\n" + str, e);
            return new Activity[0];
        }

        Activity[] arr = new Activity[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }

    public String serverInfo() {
        if (!enable) {
            return null;
        }
        // 参数
        WebResource resource = Client.create().resource("");
        ClientResponse client = resource.type(APPLICATION_JSON_TYPE).get(ClientResponse.class);
        if (client.getStatus() == 204) {
            // 成功，返回null
            return null;
        }
        if (client.getStatus() != 200) {
            // 异常
            logger.error("queryActivity error:");
        }

        return client.getEntity(String.class);
    }

    static WebResource webResource;

    public WebResource createResource() {
        if (webResource == null) {
            ClientConfig config = new DefaultClientConfig();
            Client client = Client.create(config);
            webResource = client.resource(activityApiUrl);
        }
        return webResource;
    }
}
